﻿using Adnc.Shared.Events;
using DotNetCore.CAP;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WYT.Pro.Application.Contracts.Dtos.Product;
using WYT.Pro.Application.Contracts.Services;

namespace WYT.Pro.Application.EventSubscribers
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class CapEventSubscriber : ICapSubscribe
    {
        private readonly IServiceProvider _services;
        private readonly ILogger<CapEventSubscriber> _logger;

        public CapEventSubscriber(
            IServiceProvider services
            , ILogger<CapEventSubscriber> logger)
        {
            _services = services;
            _logger = logger;
        }

        /// <summary>
        /// 修改商品库存
        /// </summary>
        /// <param name="eto"></param>
        /// <returns></returns>
        [CapSubscribe(nameof(ProductInventoryChangeEvent))]
        public async Task ProcessProductInventoryChangeEvent(ProductInventoryChangeEvent eto)
        {
            var data = eto.Data;
            using var scope = _services.CreateScope();
            var appSrv = scope.ServiceProvider.GetRequiredService<IProductAppService>();
            await appSrv.ChangeProductNum(new ProductNumChangeDto { Type = data.Type, Product = data.Product.Select(x => new ChangeDto { Id = x.Id, Num = x.Num }), Gift = data.Gift.Select(x => new ChangeDto { Id = x.Id, Num = x.Num }) });
        }
    }
}
